package com.reggie.background.controller;


import com.reggie.background.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${dish.path}")
    private String dishImgPath;

    /**
     * 上传文件并存储
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        filename=filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID().toString();
        filename=name+filename;
        File dishPath = new File(dishImgPath);
        if (!dishPath.exists()) {
            dishPath.mkdirs();
        }
        dishPath=new File(dishPath,filename);
        file.transferTo(dishPath);
        return R.success(filename);
    }

    /**
     * 读取磁盘的图片并返回前端
     * @param httpServletResponse
     * @param name
     * @throws FileNotFoundException
     */
    @GetMapping("/download")
    public void download(HttpServletResponse httpServletResponse,String name) throws IOException {
        File file = new File(dishImgPath);
        file=new File(file,name);
        log.info("本次下载的图片路径：{}",file.getAbsolutePath());
        if (!file.exists()) {
            return;
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream,httpServletResponse.getOutputStream());
        fileInputStream.close();
        return;
    }
}
